import { defineStore } from 'pinia'
import { userApi } from '@/api/user'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', {
  state: () => ({
    // 用户列表数据
    users: [],
    // 当前选中的用户
    currentUser: null,
    // 加载状态
    loading: false,
    // 分页状态
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0
    },
    // 搜索和筛选条件
    searchParams: {
      keyword: '', // 搜索关键词（用户名或邮箱）
      status: '', // 状态筛选
      dateRange: [] // 注册时间范围
    }
  }),

  getters: {
    // 获取活跃用户
    activeUsers: (state) => state.users.filter(user => user.status === 'active'),
    
    // 获取禁用用户
    inactiveUsers: (state) => state.users.filter(user => user.status === 'inactive'),
    
    // 获取被封禁用户
    bannedUsers: (state) => state.users.filter(user => user.status === 'banned'),
    
    // 获取总用户数统计
    userStats: (state) => {
      const stats = {
        total: state.users.length,
        active: 0,
        inactive: 0,
        banned: 0
      }
      
      state.users.forEach(user => {
        stats[user.status] = (stats[user.status] || 0) + 1
      })
      
      return stats
    }
  },

  actions: {
    // 获取用户列表
    async fetchUsers(params = {}) {
      this.loading = true
      try {
        const queryParams = {
          page: this.pagination.current,
          pageSize: this.pagination.pageSize,
          ...this.searchParams,
          ...params
        }
        
        const response = await userApi.getUsers(queryParams)
        this.users = response.data || []
        this.pagination.total = response.total || 0
        
        return response
      } catch (error) {
        console.error('获取用户列表失败:', error)
        ElMessage.error('获取用户列表失败')
        throw error
      } finally {
        this.loading = false
      }
    },

    // 创建用户
    async createUser(userData) {
      try {
        const response = await userApi.createUser(userData)
        
        // 刷新用户列表
        await this.fetchUsers()
        
        ElMessage.success('用户创建成功')
        return response
      } catch (error) {
        console.error('创建用户失败:', error)
        ElMessage.error('创建用户失败')
        throw error
      }
    },

    // 更新用户信息
    async updateUser(id, userData) {
      try {
        const response = await userApi.updateUser(id, userData)
        
        // 更新本地用户数据
        const index = this.users.findIndex(user => user.id === id)
        if (index !== -1) {
          this.users[index] = { ...this.users[index], ...userData }
        }
        
        ElMessage.success('用户信息更新成功')
        return response
      } catch (error) {
        console.error('更新用户失败:', error)
        ElMessage.error('更新用户失败')
        throw error
      }
    },

    // 删除用户
    async deleteUser(id) {
      try {
        await userApi.deleteUser(id)
        
        // 从本地数据中移除用户
        this.users = this.users.filter(user => user.id !== id)
        this.pagination.total -= 1
        
        ElMessage.success('用户删除成功')
      } catch (error) {
        console.error('删除用户失败:', error)
        ElMessage.error('删除用户失败')
        throw error
      }
    },

    // 批量删除用户
    async batchDeleteUsers(userIds) {
      try {
        await userApi.batchDeleteUsers(userIds)
        
        // 从本地数据中移除用户
        this.users = this.users.filter(user => !userIds.includes(user.id))
        this.pagination.total -= userIds.length
        
        ElMessage.success(`成功删除 ${userIds.length} 个用户`)
      } catch (error) {
        console.error('批量删除用户失败:', error)
        ElMessage.error('批量删除用户失败')
        throw error
      }
    },

    // 更新用户状态
    async updateUserStatus(id, status) {
      try {
        await userApi.updateUserStatus(id, status)
        
        // 更新本地用户状态
        const index = this.users.findIndex(user => user.id === id)
        if (index !== -1) {
          this.users[index].status = status
        }
        
        ElMessage.success('用户状态更新成功')
      } catch (error) {
        console.error('更新用户状态失败:', error)
        ElMessage.error('更新用户状态失败')
        throw error
      }
    },

    // 搜索用户
    async searchUsers(keyword) {
      this.searchParams.keyword = keyword
      this.pagination.current = 1 // 重置到第一页
      await this.fetchUsers()
    },

    // 筛选用户
    async filterUsers(filters) {
      this.searchParams = { ...this.searchParams, ...filters }
      this.pagination.current = 1 // 重置到第一页
      await this.fetchUsers()
    },

    // 重置搜索和筛选条件
    resetSearchParams() {
      this.searchParams = {
        keyword: '',
        status: '',
        dateRange: []
      }
    },

    // 设置分页参数
    setPagination(pagination) {
      this.pagination = { ...this.pagination, ...pagination }
    },

    // 设置当前用户
    setCurrentUser(user) {
      this.currentUser = user
    },

    // 清空当前用户
    clearCurrentUser() {
      this.currentUser = null
    }
  }
})